import { RefObject, useEffect, useState } from 'react'
import { Form, Input, Button, Picker, PickerRef, Toast, Space, Mask, DotLoading } from 'antd-mobile';
import styles from './App.module.scss';
import 'normalize.css/normalize.css'
import { useRequest, useTitle } from 'ahooks';
import { get, put } from './utils/request';
function App() {
  useTitle('欢迎评审专家签到')
  // 身份证校验获取信息
  const [exportCodeBtnDisabeled, setExportCodeBtnDisabeled] = useState(true)
  const [formDisabled, setFormDisabled] = useState(true)
  const [visible, setVisible] = useState(false)
  const [expertCodeForm] = Form.useForm()
  const [expertForm] = Form.useForm()
  const {data: bakList = [], loading, run: getBakList} = useRequest(async() => {
    let data = await get('banks/findBankList')
    data = data.map((item: any) => {
      return {
        label: item.bankfullname,
        value: item.id
      }
    })
    return data as Array<{ label: string, value: string}>
  }, {
    manual: true,
    debounceWait: 1000,

  })
  useEffect(() => {
    getBakList()
  }, [])

  const getExpertInfo = async (expertCode: string) => {
    expertForm.resetFields()
    let data = await get('expert/findExpert', {expertCode})
    if (data.code) {
      Toast.show({
        icon: 'fail',
        content: data.message,
      })
      return
    }
    expertForm.setFieldsValue(data)
    expertForm.setFieldValue('bank_id', [data.bank_id])
    setFormDisabled(false)
    return data
  }
  const { data: expertInfo = {}, loading: expertInfoLoading, run: getExpertInfoByCode }  = useRequest(getExpertInfo, {
    manual: true,
    debounceWait: 500,
  })

  const updateExpertInFo = async (expertInfo: any) => {
    put(`expert/updataExpert/${expertInfo.id}`, expertInfo).then((e) => {
      setVisible(false)
      if(e.code<9999){
        Toast.show({
          icon: 'success',
          content: '签到成功',
        })
      } else {
        Toast.show({
          icon: 'fail',
          content: '签到失败',
        })
      }
    }).catch(() => {
      setVisible(false)
      Toast.show({
        icon: 'fail',
        content: '签到失败,请联系项目员',
      })
    })
  }
  const {run: updateExpert, loading: updateExpertInfoLoading} = useRequest(updateExpertInFo, {
    manual: true,
    debounceWait: 500,
  })

  const handleExpertCodeClick = () => {
    const [isExpertCodeValid] = expertCodeForm.getFieldError('expert_code')
    if (isExpertCodeValid !== undefined) return
    const expertCode = expertCodeForm.getFieldValue('expert_code')
    getExpertInfoByCode(expertCode)
  }
  
  const ExportCodeFormElement:React.FC = () =>  {
    return (
      <Form form={expertCodeForm} onValuesChange={() => setExportCodeBtnDisabeled(false)} initialValues={{expert_code: ''}}>
        <Form.Item
            name='expert_code'
            label='身份证号'
            rules={[{ required: true, pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/, message: '请输入正确的身份证号' }]}
            extra={<Button color="warning" disabled={exportCodeBtnDisabeled} onClick={handleExpertCodeClick} loading={expertInfoLoading}>校验</Button>}
        >
          <Input placeholder='请录入身份证号'></Input>
        </Form.Item>
      </Form>
    )
  }

  const MaskContent: React.FC = () => {
    return (
      <>
        <Mask visible={visible}>
          <div className={styles.maskContent}>
            <Space direction='vertical' align="center">
              <DotLoading></DotLoading>
              <span>签到信息提交中</span>
            </Space>
          </div>
        </Mask>
      </>
    )
  }


  const onFinish = (values: any) => {
    values.bankcode = values.bank_id[0]
    values.id = expertInfo.id
    updateExpertInFo(values)
  }
  return (
   <div className={styles.container}>
    <div className={styles.header}>
      <h2 className={styles.title}>广东元正招标采购有限公司</h2>
      <img src="http://j.eebidding.com/img/ico.c0cab98f.jpg" width="80" height="80" ></img>
    </div>
    <Form layout='horizontal'  form={expertForm} disabled={formDisabled} 
      onFinish={onFinish}
      footer={
        <Button block color="warning" disabled={formDisabled} loading={updateExpertInfoLoading} type='submit' size='large'>
          提交签到信息
        </Button>
      }>
        <ExportCodeFormElement/>
      <Form.Item
          name='expert_name'
          label='姓名'
          disabled
      >
        <Input></Input>
      </Form.Item>
      <Form.Item
          name='telephone'
          label='手机号'
          rules={[{ required: true,pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/, message: '请录入正确的手机号' }]}
      >
        <Input placeholder='请输入手机号'></Input>
      </Form.Item>
      <Form.Item
          name='company_name'
          label='工作单位'
          rules={[{ required: true, message: '请录入工作单位' }]}
      >
        <Input placeholder='请录入工作单位'></Input>
      </Form.Item>
      <Form.Item
          name='position'
          label='职务'
      >
        <Input></Input>
      </Form.Item>
      <Form.Item
          name='technical_title'
          label='职称'
      >
        <Input placeholder='请采购人录入职称'></Input>
      </Form.Item>
      <Form.Item
          name='bank_id'
          trigger='onConfirm'
          label='开户银行'
          rules={[{required:true, message: '请选择开户银行' }, {validator: (_, value) =>{
            const val = value[0]
            if (val !== '') {
              return Promise.resolve()
            }
            return Promise.reject(new Error('请选择开户银行'))
          }}]}
          onClick={(e, pickerRef: RefObject<PickerRef>) => {
            pickerRef.current?.open() // ⬅️
          }}
      >
        <Picker
          columns={[bakList]}
        >
          {(items, { open }) => {
            return (
              <Space align='center'>
                {items.every(item => item === null)
                  ? '请选择开户银行'
                  : items.map(item => item?.label ?? '未选择').join(' - ')}
              </Space>
            )
          }}
        </Picker>
      </Form.Item>
      <Form.Item
          name='bank_account'
          label='银行卡号'
          rules={[{required:true,pattern: /^[1-9]\d{9,29}$/, message: '请输入正确的银行卡号' }]}
      >
        <Input placeholder='请录入银行卡号'></Input>
      </Form.Item>
    </Form>
    <div className={styles.desc}>
      <span>温馨提示</span>
      <p>1.为减少专家签到的繁琐,请专家核对以上信息并补充不完整的信息;</p>

      <p>2.本次评审专家评标费使用网银支付,请录入您本人的银行卡信息。</p>
    </div>
    <MaskContent></MaskContent>
   </div>
  )
}

export default App;
